package com.hxc.aop;


import com.hxc.entity.OperateLog;
import com.hxc.mapper.OperateLogMapper;
import com.hxc.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 基于AOP实现日志记录
 * */
@Aspect // 暂时关闭切面
@Component
public class OperationLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    //HttpServletRequest它代表一次 HTTP 请求，由浏览器（客户端）发送到服务器时自动创建。
    //通过这个对象，你可以获取与该请求有关的各种信息
    private HttpServletRequest request; //
    @Around("@annotation(com.hxc.anno.Log)")
    public Object logOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        // 记录开始时间
        long start = System.currentTimeMillis();
        // 执行目标方法并获取返回值
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        // 计算耗时
        long cost = end - start;
        // 获取当前操作用户id
        // (1)从请求头中取出 token
        String token = request.getHeader("token");
        // (2)解析token
        Claims claims = JwtUtils.parseJWT(token);
        // (3)得到Id
        Integer empId = (Integer)claims.get("id");
        // 构建log实体类
        OperateLog log = new OperateLog();
        log.setOperateEmpId(empId);
        log.setOperateTime(LocalDateTime.now()); //操作时间
        log.setClassName(joinPoint.getTarget().getClass().getName());//类名
        log.setMethodName(joinPoint.getSignature().getName()); //方法名
        log.setMethodParams(Arrays.toString(joinPoint.getArgs()));//设置参数
        log.setReturnValue(result.toString()); //设置返回值
        log.setCostTime(cost);
        operateLogMapper.insert(log);
        return result;
    }
}
